<template>
  <!-- 顶部导航栏 -->
  <van-nav-bar title="确认订单" @click-left="onClickLeft" fixed>
    <template #left>
      <van-icon name="arrow-left" size="24" color="#000" />
    </template>
    <template #right>
      <van-icon name="ellipsis" size="24" color="#000" />
    </template>
  </van-nav-bar>

  <div class="settlement-container">
    <!-- 顶部游戏列表 -->
    <div class="game-list">
      <!-- title -->
      <div class="bar-1">
        <div class="title">CDKEY (游戏)</div>
        <van-notice-bar left-icon="volume-o" :scrollable="false">
          <van-swipe vertical class="notice-swipe" :autoplay="3000" :show-indicators="false">
            <van-swipe-item>PC游戏都是以CDKEY形式发货哦~</van-swipe-item>
            <van-swipe-item>购买主机游戏时请仔细检查收货地址！</van-swipe-item>
          </van-swipe>
        </van-notice-bar>
      </div>
      <!-- 列表 -->
      <div class="bar-2">
        <template v-for="item in gameInfo">
          <div class="list-item">
            <div class="game-img">
              <van-image width="150" height="75" radius="3px" :src="item.coverUrl" />
            </div>
            <div class="game-info">
              <div class="row-1">
                <p class="game-name">{{ item.gameName }}</p>
                <p class="goods-describe">CDKEY发货</p>
              </div>
              <div class="row-2">
                <span class="price-currency">￥</span>
                <span class="game-price" style="margin-left: 2px;">{{ item.currentPrice }}</span>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <!-- 支付方式 -->
    <div class="payment-method">
      <div class="bar-1">
        <div class="title">支付方式</div>
      </div>
      <div class="bar-2">
        <div>
          <van-radio-group v-model="checked">
            <van-cell-group>
              <van-cell title="iGame余额支付" clickable @click="changeRaido('0')" icon="gem"
                :label="'余额剩余:￥' + userStore.userInfo.accountBalance">
                <template #right-icon>
                  <van-radio checked-color="#14191e" name="0" />
                </template>
              </van-cell>
              <van-cell title="微信支付" clickable @click="changeRaido('1')" icon="wechat-pay">
                <template #right-icon>
                  <van-radio checked-color="green" name="1" />
                </template>
              </van-cell>
              <van-cell title="支付宝支付" clickable @click="changeRaido('2')" icon="alipay">
                <template #right-icon>
                  <van-radio name="2" />
                </template>
              </van-cell>
            </van-cell-group>
          </van-radio-group>
        </div>
      </div>
    </div>
    <!-- 优惠券 -->
    <div class="coupon">
      <div class="bar-1">
        <div class="title van-hairline--bottom">优惠券</div>
      </div>
      <div class="bar-2">
        <!-- 优惠券单元格 -->
        <van-coupon-cell :coupons="coupons" :chosen-coupon="chosenCoupon" @click="showList = true" />
        <van-popup v-model:show="showList" round position="bottom" style="height: 90%; padding-top: 4px;">
          <!-- 优惠券列表 -->
          <van-coupon-list :coupons="coupons" :chosen-coupon="chosenCoupon" :disabled-coupons="disabledCoupons"
            @change="onChange" @exchange="onExchange" />
        </van-popup>
      </div>
    </div>
  </div>
  <!-- 提交订单栏 -->
  <van-submit-bar class="van-hairline--top" :price="finalPrice - couponPrice" button-text="提交订单" @submit="onSubmit" />
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';

import { Toast } from 'vant'

import router from '../../route';

import { useCartStore } from '../../store/shoppingCart';
import { useUserStore } from '../../store/user';


import { getGameDetail } from '../../network/gameDetail'
import { getCoupons, exchangeCoupons, deleteCoupons } from '../../network/coupon'

const cartStore = useCartStore()
const userStore = useUserStore()

// 获取store中所有待购买的游戏的id
const gameIdLists = userStore.placeOrder.map(item => {
  return item.gameId
})

// 获取游戏详细数据
const gameInfo = reactive([])
onMounted(() => {
  gameIdLists.forEach(item => {
    getGameDetail(item).then(res => {
      const { data: result } = res
      gameInfo.push(result)
    })
  })
})

// 可用优惠券
const coupons = ref([])
// 不可用优惠券
const disabledCoupons = ref([])
onMounted(() => {
  // 获取用户拥有的优惠券
  getCoupons(userStore.userInfo.id).then(res => {
    const { data: result } = res
    // 判断优惠券能否被当前商品使用
    for (let item of result) {
      if (gameIdLists.includes(item.id) || item.id === 999) {
        coupons.value.push(item)
      } else {
        disabledCoupons.value.push(item)
      }
    }
  })
})

// 展示优惠券列表
const showList = ref(false)
// 默认的选择优惠券
const chosenCoupon = ref(-1)
// 优惠券优惠额度
const couponPrice = ref(0)
// 当前选择的优惠券的序号
const couponIndex = ref(-1)
// 选择优惠券
const onChange = (index) => {
  if (index === -1) { // 不使用优惠券
    showList.value = false;
    chosenCoupon.value = index;
    couponPrice.value = 0
  } else {
    couponIndex.value = index
    showList.value = false;
    chosenCoupon.value = index;
    couponPrice.value = coupons.value[index].value
  }
}
// 兑换优惠券
const onExchange = (code) => {
  exchangeCoupons({
    id: 999,
    condition: '无门槛减10元',
    reason: '',
    value: 1000,
    name: '测试专用',
    startAt: 1640966400,
    endAt: 1672502400,
    valueDesc: '10',
    unitDesc: '元',
    userId: userStore.userInfo.id
  }).then(res => {
    Toast(res.data)
    // 获取用户拥有的优惠券
    getCoupons(userStore.userInfo.id).then(res => {
      // 重置优惠券列表
      coupons.value.length = 0
      disabledCoupons.value.length = 0
      const { data: result } = res
      // 判断优惠券能否被当前商品使用
      for (let item of result) {
        if (gameIdLists.includes(item.id) || item.id === 999) {
          coupons.value.push(item)
        } else {
          disabledCoupons.value.push(item)
        }
      }
    })
  })
}

// 最终售价
const finalPrice = computed(() => {
  let price = 0
  for (let item of gameInfo) {
    price += item.currentPrice
  }
  return price * 100
})

// 选择支付方式
const checked = ref('0')
const changeRaido = (index) => {
  checked.value = index
}

// 提交订单按钮
const onSubmit = () => {
  if (Number(checked.value) === 0) {
    // 判断用户余额是否足够
    if (userStore.userInfo.accountBalance >= ((finalPrice.value - couponPrice.value) / 100)) {
      // 从用户余额中扣除本次消费的金额
      userStore.userInfo.accountBalance -= ((finalPrice.value - couponPrice.value) / 100)
      // 如果使用了优惠券，则在数据库中删除已经使用过的优惠券
      if (couponIndex.value !== -1) {
        let currentCoupons = coupons.value[couponIndex.value]
        deleteCoupons({
          id: currentCoupons.id,
          userId: currentCoupons.userId
        }).then(res => {
          console.log(res.data);
        })
      }
      // 购买成功，删除购物车中已经购买的商品
      gameIdLists.forEach(key => {
        if (cartStore.cartsGame.includes(key)) {
          cartStore.cartsGame.splice(cartStore.cartsGame.indexOf(key), 1)
        }
      })
      Toast('购买成功~')
      setTimeout(() => {
        history.back()
      }, 1000)
    } else {
      Toast('您的余额不足~')
    }
  } else if (Number(checked.value) === 1) {
    Toast('微信支付')
  } else if (Number(checked.value) === 2) {
    Toast('支付宝支付')
  }
}

// 点击左侧按钮返回上级路由
const onClickLeft = () => {
  history.back()
}
</script>

<style scoped>
.settlement-container {
  margin-top: 46px;
  margin-bottom: 50px;
  background-color: #fff;
}

.notice-swipe {
  height: 40px;
  line-height: 40px;
}

/* 顶部游戏列表 */
.bar-1 {
  border-top: 5px solid #f2f3f5;
}

.bar-2 .list-item:not(:last-child) {
  border-bottom: 1px solid #f2f3f5;
}

.game-list .title {
  padding: 12px 12px;
  font-size: 14px;
  font-weight: 600;
  line-height: 20px;
  color: #323233;
}

.game-list .list-item {
  padding: 12px 12px;
  display: flex;
}

.game-list .list-item .game-info {
  margin-left: 10px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.game-list .list-item .game-info .row-1 .game-name {
  font-size: 15px;
  font-weight: 500;
  line-height: 21px;
  color: #323233;
}

.game-list .list-item .game-info .row-1 .goods-describe {
  margin-top: 3px;
  font-size: 12px;
  line-height: 16px;
  font-weight: 400;
  color: #c8c9cc;
}

.game-list .list-item .game-info .row-2 .price-currency {
  font-size: 13px;
  line-height: 19px;
  font-weight: 500;
}

.game-list .list-item .game-info .row-2 .game-price {
  font-size: 17px;
  line-height: 23px;
  font-weight: 500;
}

/* 支付方式 */
.payment-method .bar-1 .title {
  padding: 12px 12px;
  font-size: 14px;
  font-weight: 600;
  line-height: 20px;
  color: #323233;
}

/* 优惠券 */
.coupon .bar-1 .title {
  padding: 12px 12px;
  font-size: 14px;
  font-weight: 600;
  line-height: 20px;
  color: #323233;
}
</style>
